using System.IO;

namespace FileDirUtils
{
    public class FileCompareContent : IFileCompare
    {
        private FileStream OpenFile(string fileName)
        {
            try
            {
                FileInfo fi = new FileInfo(fileName);
                FileStream fs = fi.OpenRead();
                return fs;
            }
            catch
            { }
            return null;

        }
        bool CompareByteArrays(byte[] b1, byte[] b2)
        {
            for(long i = 0; i < b1.Length; i++)
                if (b1[i] != b2[i])
                    return false;
            return true;
        }
        public FileCompareResult CompareFiles(string fileName1, string fileName2)
        {
            FileStream f1 = OpenFile(fileName1);
            if (f1 == null)
                return FileCompareResult.File1_Not_Existing;

            FileStream f2 = OpenFile(fileName2);
            if (f2 == null)
                return FileCompareResult.File2_Not_Existing;
           
            if (f1.Length != f2.Length)
                return FileCompareResult.Different_Size;

            long blockSize = 4096;
            byte[] b1 = new byte[blockSize];
            byte[] b2 = new byte[blockSize];
            
            long offset = 0;
            FileCompareResult res = FileCompareResult.OK;
            for (long fs = f1.Length; fs > 0; fs -= blockSize)
            {
                blockSize = blockSize > fs ? fs : blockSize;
                f1.Read(b1, (int) offset, (int) blockSize);
                f2.Read(b2, (int) offset, (int) blockSize);
                offset += blockSize;
                if (CompareByteArrays(b1, b2) != true)
                {
                    res = FileCompareResult.Different_Content;
                    break;
                }
            }
            f1.Close();
            f2.Close();
            return res;
        }
    }
}